import style from './app.module.scss'
import React, { useEffect, useState } from 'react'
import { Routes, Route, useNavigate } from 'react-router-dom'
import { CurrentUserContext } from '../../contexts/CurrentUserContext'
import ProtectedRoute from '../ProtectedRoute/ProtectedRoute'
import NotFound from '../NotFound404/notFound'
import Register from '../Register/register'
import Login from '../Login/login'
import { mainApi, mainApiAuth } from '../../utils'
import { ILogin, IRegister, IToken, IUser } from '../../interfaces'
import ToDos from '../ToDos/ToDos'
import { useLocation } from 'react-router-dom'

function App() {
  const [isLoggedIn, setIsLoggedIn] = useState<boolean>(false)
  const [serverError, setServerError] = useState<string>('')
  const [error, setError] = useState<string>(null)

  const [currentUser, setCurrentUser] = useState<IUser>(null)

  const navigate = useNavigate()
  const location = useLocation()

  const checkAuth = () => {
    if (!localStorage.getItem("jwt")) {
      setIsLoggedIn(false)
      navigate("/signin")
    }
    mainApiAuth.checkToken(localStorage.getItem("jwt"))
      .then(res => {
        if (res) {
          setIsLoggedIn(true)
        }
      })
      .catch(err => {
        setIsLoggedIn(false)
        navigate("/signin")
        console.log(err)
      })
  }
  useEffect(() => {
    checkAuth()
  }, [isLoggedIn])

  useEffect(() => {
    if (!isLoggedIn) return
    mainApi
      .getUserInfo()
      .then((data) => {
        setCurrentUser(data)
      })
      .catch((err) => console.log(err))
  }, [isLoggedIn])

  function onSignOut() {
    localStorage.removeItem("jwt");
    setIsLoggedIn(false)
  }

  async function handleUpdateUser(data) {
    try {
      const res = await mainApi.setUserInfo(data);
      setCurrentUser(res)
    } catch (err) {
      setError("Ошибка при обновлении данных пользователя");
      setTimeout(() => {
        setError("")
      }, 3000)
    }
  }

  async function handleRegister(registerData: IRegister) {
    try {
      const {name, email, password} = registerData
      const res = await mainApiAuth.signup({ name, email, password });
      if (res.status === "error") {
        throw new Error(res.message);
      } else {
        debugger
        setCurrentUser(res);
        handleLogin( { email, password })
      }
    } catch (error) {
      setServerError("Произошла ошибка при регистрации");
      setTimeout(() => {
        setServerError("");
      }, 3000);
    }
  }

  async function handleLogin(loginData: ILogin) {
    try {
      const {email, password} = loginData
      const res: IToken = await mainApiAuth.signin({ email, password })
      localStorage.setItem("jwt", res.token);
      setIsLoggedIn(true)
      navigate("/todos")
    } catch (error) {
      setServerError("Произошла ошибка при авторизации");
      setTimeout(() => {
        setServerError("")
      }, 3000)
    }
  }

  return (
    <CurrentUserContext.Provider value={currentUser}>
      <div className={style.page}>
        <Routes>
          {/*<Route*/}
          {/*  path="/movies"*/}
          {/*  element={*/}
          {/*    <ProtectedRoute element={Movies} isLoggedIn={isLoggedIn} />*/}
          {/*  }*/}
          {/*/>*/}
          {/*<Route*/}
          {/*  path="/saved-movies"*/}
          {/*  element={*/}
          {/*    <ProtectedRoute element={SavedMovies} isLoggedIn={isLoggedIn} />*/}
          {/*  }*/}
          {/*/>*/}
          {/*<Route*/}
          {/*  path="/profile"*/}
          {/*  element={*/}
          {/*    <ProtectedRoute*/}
          {/*      element={Profile}*/}
          {/*      onSignOut={onSignOut}*/}
          {/*      isLoggedIn={isLoggedIn}*/}
          {/*      onUpdateUser={handleUpdateUser}*/}
          {/*      error={error}*/}
          {/*    />*/}
          {/*  }*/}
          {/*/>*/}
          <Route path="/" element={<ToDos />} />
          <Route
            path="/todos"
            element={
              <ProtectedRoute element={ToDos} isLoggedIn={isLoggedIn} />
            }
          />
          <Route
            path="/signup"
            element={
              <Register
                onRegister={handleRegister}
                serverError={serverError}
                isLoggedIn={isLoggedIn}
              />
            }
          />
          <Route
            path="/signin"
            element={
              <Login
                onLogin={handleLogin}
                serverError={serverError}
                isLoggedIn={isLoggedIn}
              />
            }
          />
          <Route path="*" element={<NotFound />} />
        </Routes>
      </div>
    </CurrentUserContext.Provider>
  )
}

export default App;
